import React from 'react';
import ReactDOM from 'react-dom';
import TodoApp from './components/TodoApp.js'
import {createStore} from 'redux'
//生成store
var store=createStore(reducer,{list:[]});

//声明reducer 他是一个纯函数，必须要返回全新的state  。然后将这个方法作为上一个步骤的第一个参数
function reducer(state,action){
	//根据action的类型的不同执行不同的处理
	switch(action.type){
		case 'ADD_TODO':
			state.list.push(action.text);
			var newState=Object.assign({},state,{
				list:state.list
			})
			return newState;
			break;
		case "REMOVE_TODO":
			state.list.splice(action.index,1);
			var newState=Object.assign({},state,{
				list:state.list
			})
			return newState;
			break;
		default:
			return state;

	}
}

//监听页面渲染  使用store.subscribe(fn)
function render(){
	ReactDOM.render(
		<TodoApp AddTodo={addTodo} Removeli={removeTodo} list={store.getState().list}/>,
		document.querySelector('#box')
	)
}
store.subscribe(render);

//手动触发一个渲染
render();

function addTodo(action){
	store.dispatch(action);
}

function removeTodo(action){
	store.dispatch(action);
}